// Handle extension installation or update
chrome.runtime.onInstalled.addListener((details) => {
  console.log('Extension installed/updated:', details.reason);
  try {
    // Initialize default settings
    chrome.storage.local.set({
      enabled: false,
      tool: 'pen',
      color: '#FF0000',
      canUndo: false,
      canRedo: false
    });
    console.log('Web Canvas: Successfully initialized default settings');
  } catch (error) {
    console.error('Web Canvas: Failed to initialize settings:', error);
  }
});

// Handle extension activation
chrome.action.onClicked.addListener((tab) => {
  if (tab.url.startsWith('chrome://')) {
    console.log('Cannot inject into chrome:// pages');
    return;
  }
  console.log('Extension activated on tab:', tab.id);
});

// Handle messages from content script and popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('Background script received message:', message);
  
  if (message.action === 'contentScriptReady') {
    console.log('Content script ready in tab:', sender.tab?.id);
  }
  
  sendResponse({ success: true });
  return true;
});

// Handle tab updates
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete' && !tab.url?.startsWith('chrome://')) {
    console.log('Tab loaded, checking content script:', tabId);
    // Check if canvas should be enabled for this tab
    try {
      chrome.storage.local.get(['enabled'], function(result) {
        if (result.enabled) {
          chrome.tabs.sendMessage(tabId, {
            action: 'toggleCanvas',
            enabled: true
          }).catch(error => {
            // Ignore errors when content script is not yet loaded
            if (!error.message.includes('receiving end does not exist')) {
              console.error('Web Canvas: Failed to send message to tab:', error);
            }
          });
        }
      });
    } catch (error) {
      console.error('Web Canvas: Failed to check canvas state:', error);
    }
  }
});

// Listen for tab activation
chrome.tabs.onActivated.addListener(function(activeInfo) {
  try {
    chrome.storage.local.get(['enabled'], function(result) {
      if (result.enabled) {
        chrome.tabs.sendMessage(activeInfo.tabId, {
          action: 'toggleCanvas',
          enabled: true
        }).catch(error => {
          // Ignore errors when content script is not yet loaded
          if (!error.message.includes('receiving end does not exist')) {
            console.error('Web Canvas: Failed to send message to tab:', error);
          }
        });
      }
    });
  } catch (error) {
    console.error('Web Canvas: Failed to handle tab activation:', error);
  }
});
